package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
	"strconv"
)

var commentLogger = log.GetLogger()

func writecommentLoggerLoggerLog(funcName, errMsg string, err error) {
	commentLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "comment.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func CreatComment(c echo.Context) error {
	comment := model.Comment{}
	err := c.Bind(&comment)
	if err != nil {
		writecommentLoggerLoggerLog("CreatComment", "param wrong", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	if comment.Text == "" {
		writecommentLoggerLoggerLog("CreatComment", config.ErrorContent, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorContent)
	}

	flag, err := model.PostWeixinMsgSecCheck(comment.Text)
	if flag == false {
		writecommentLoggerLoggerLog("CreatComment", "内容违规1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "内容违规")
	}
	if err != nil {
		writecommentLoggerLoggerLog("CreatComment", "内容违规2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "内容违规")
	}

	id := context.GetJWTUserOpenid(c)
	comment.UserID = id

	//创建Comment
	comment, err = model.CreateComment(comment)
	if err != nil {
		writecommentLoggerLoggerLog("CreatComment", config.ErrorCommentCreat, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentCreat)
	}

	//创建通知消息
	if comment.ForumposterId != comment.UserID {
		M := model.Message{}
		M.Anonymity = comment.Anonymity
		M.Type = 11
		M.ForumPostId = comment.ForumpostId
		M.UserID = comment.ForumposterId
		M.ContentId = comment.ForumpostId
		M.ActionUserId = comment.UserID
		M.ActionContentId = comment.ID.Hex()
		err = model.CreatMessage(M)
		if err != nil {
			writecommentLoggerLoggerLog("CreatComment", config.ErrorMessageCreat, err)
			return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageCreat)
		}
	}

	//更新帖子回复数目
	err = model.UpdateForumpostReply(comment.ForumpostId, 1)
	if err != nil {
		writecommentLoggerLoggerLog("CreatComment", config.ErrorUpdateForumpostReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostReply)
	}

	//更新帖子分数
	err = model.UpdateForumpostScore(comment.ForumpostId, config.CommentScore)
	if err != nil {
		writecommentLoggerLoggerLog("CreatComment", config.ErrorUpdateForumpostScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}

	resData := map[string]interface{}{}
	resData["comment"] = comment

	return context.RetData(c, resData)
}

func DeleteComment(c echo.Context) error {
	id := param.Id{}
	err := c.Bind(&id)
	if err != nil {
		writecommentLoggerLoggerLog("DeleteComment", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	UserID := context.GetJWTUserOpenid(c)

	//删除评论
	comment, err := model.DeleteComment(id.Id, UserID, false)
	if err != nil {
		writecommentLoggerLoggerLog("DeleteComment", config.ErrorCommentDelete, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentDelete)
	}

	//query := bson.M{
	//	"content_id":id.Id,
	//}
	//_ = model.DeleteMessageAll(query)

	//更新帖子回复数目
	err = model.UpdateForumpostReply(comment.ForumpostId, -1)
	if err != nil {
		writecommentLoggerLoggerLog("DeleteComment", config.ErrorUpdateForumpostReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostReply)
	}

	//更新帖子分数
	err = model.UpdateForumpostScore(comment.ForumpostId, -config.CommentScore)
	if err != nil {
		writecommentLoggerLoggerLog("DeleteComment", config.ErrorUpdateForumpostScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}

	//删除所有回复
	reply := []model.Reply{}
	reply, err = model.GetReplyByCommentALL(comment.ID.Hex())
	for i := 0; i < len(reply); i++ {
		//		query := bson.M{
		//			"content_id":reply[i].ID.Hex(),
		//		}
		//		_ = model.DeleteMessageAll(query)
		_, _ = model.DeleteReply(reply[i].ID.Hex(), reply[i].UserID, true)
	}

	//删除消息
	if comment.ForumposterId != comment.UserID {
		m := model.Message{}
		m.Type = 11
		m.UserID = comment.ForumposterId
		m.ContentId = comment.ForumpostId
		m.ActionUserId = comment.UserID
		m.ActionContentId = comment.ID.Hex()
		err = model.DeleteMessage(m)
		if err != nil {
			writecommentLoggerLoggerLog("DeleteComment", config.ErrorMessageDelete, err)
			return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageDelete)
		}
	}

	return context.RetData(c, "")
}

func GetCommentByForumpost(c echo.Context) error {
	comment := param.GetComment{}
	var err error
	comment.Page, err = strconv.Atoi(c.QueryParam("page"))
	comment.PerPage, err = strconv.Atoi(c.QueryParam("per_page"))
	comment.Postid = c.QueryParam("post_id")
	if err != nil || comment.Page == 0 || comment.PerPage <= 0 || comment.Postid == "" {
		writecommentLoggerLoggerLog("GetCommentByForumpost", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	user_id := ""
	var ParamComment param.Comment
	var ParamComments []param.Comment
	resData := map[string]interface{}{}
	Comment, err := model.GetCommentByForumpost(comment.Postid, comment.Page, comment.PerPage, user_id)
	if err != nil {
		writecommentLoggerLoggerLog("GetCommentByForumpost", config.ErrorCommentGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentGet)
	}
	for i := 0; i < len(Comment); i++ {
		if Comment[i].ForumpostAnonymity == true {
			Comment[i].ForumposterId = ""
		}
		ParamComment.Comment = Comment[i]
		ParamComment.Reply, _ = model.GetReplyByComment(Comment[i].ID.Hex(), 1, 5, user_id)
		ParamComments = append(ParamComments, ParamComment)
	}
	if len(ParamComments) != 0 {
		resData["comments"] = ParamComments
	} else {
		resData["comments"] = []param.Comment{}
	}

	return context.RetData(c, resData)
}
func GetCommentByForumpost1(c echo.Context) error {
	comment := param.GetComment{}
	var err error
	comment.Page, err = strconv.Atoi(c.QueryParam("page"))
	comment.PerPage, err = strconv.Atoi(c.QueryParam("per_page"))
	comment.Postid = c.QueryParam("post_id")
	if err != nil || comment.Page == 0 || comment.PerPage <= 0 || comment.Postid == "" {
		writecommentLoggerLoggerLog("GetCommentByForumpost", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	user_id := context.GetJWTUserOpenid(c)

	var ParamComment param.Comment
	var ParamComments []param.Comment
	resData := map[string]interface{}{}
	Comment, err := model.GetCommentByForumpost(comment.Postid, comment.Page, comment.PerPage, user_id)
	if err != nil {
		writecommentLoggerLoggerLog("GetCommentByForumpost", config.ErrorCommentGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentGet)
	}
	for i := 0; i < len(Comment); i++ {
		if Comment[i].ForumpostAnonymity == true {
			Comment[i].ForumposterId = ""
		}
		ParamComment.Comment = Comment[i]
		ParamComment.Reply, _ = model.GetReplyByComment(Comment[i].ID.Hex(), 1, 5, user_id)
		ParamComments = append(ParamComments, ParamComment)
	}
	if len(ParamComments) != 0 {
		resData["comments"] = ParamComments
	} else {
		resData["comments"] = []param.Comment{}
	}

	return context.RetData(c, resData)
}

func StarComment(c echo.Context) error {
	star := param.Star{}
	err := c.Bind(&star)
	if err != nil {
		writecommentLoggerLoggerLog("StarComment", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	user_id := context.GetJWTUserOpenid(c)

	err = model.StarComment(star.Id, user_id, star.Action == 1)
	if err != nil {
		writecommentLoggerLoggerLog("StarComment", config.ErrorCommentStar, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentStar)
	}

	comment, err := model.GetCommentByid(star.Id, user_id)
	if err != nil {
		writecommentLoggerLoggerLog("StarComment", config.ErrorCommentGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentGet)
	}

	if comment.UserID != user_id {
		M := model.Message{}
		M.Type = 15
		M.ForumPostId = comment.ForumpostId
		M.UserID = comment.UserID
		M.ContentId = comment.ID.Hex()
		M.ActionUserId = user_id
		if star.Action == 1 {
			err = model.CreatMessage(M)
			if err != nil {
				writecommentLoggerLoggerLog("StarComment", config.ErrorMessageCreat, err)
				return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageCreat)
			}
			err = model.UpdateCommentScore(star.Id, config.StarScore)
		} else {
			err = model.DeleteMessage(M)
			if err != nil {
				writecommentLoggerLoggerLog("StarComment", config.ErrorMessageDelete, err)
				return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageDelete)
			}
			err = model.UpdateCommentScore(star.Id, -config.StarScore)
		}
		if err != nil {
			writecommentLoggerLoggerLog("StarComment", config.ErrorUpdateCommentScore, err)
			return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentScore)
		}
	}

	return context.RetData(c, "")
}

func GetCommentById(c echo.Context) error {
	id := param.Id{}
	id.Id = c.QueryParam("id")
	var err error
	if id.Id == "" {
		writecommentLoggerLoggerLog("GetCommentById", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	user_id := context.GetJWTUserOpenid(c)

	resData := map[string]interface{}{}
	comment, err := model.GetCommentByid(id.Id, user_id)
	if err != nil {
		writecommentLoggerLoggerLog("GetCommentById", config.ErrorCommentGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentGet)
	}
	if comment.ForumpostAnonymity == true {
		comment.ForumposterId = ""
	}
	var ParamComment param.Comment
	ParamComment.Comment = comment
	ParamComment.Reply, _ = model.GetReplyByComment(comment.ID.Hex(), 1, 5, user_id)
	resData["comments"] = ParamComment
	return context.RetData(c, resData)
}

func TipoffComment(c echo.Context) error {
	action := param.Tipoff{}
	err := c.Bind(&action)
	if err != nil {
		writecommentLoggerLoggerLog("TipoffComment", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	user_id := context.GetJWTUserOpenid(c)

	Tipoff := model.Tipoff{
		User_id:    user_id,
		Context_id: action.Id,
		Text:       action.Text,
		Level:      1,
	}

	Tipoff, err = model.CreateTipoff(Tipoff)
	if err != nil {
		writecommentLoggerLoggerLog("TipoffComment", "举报失败", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "举报失败")
	}

	err = model.UpdateCommentScore(action.Id, -config.TipoffScore)
	if err != nil {
		writecommentLoggerLoggerLog("TipoffComment", config.ErrorUpdateCommentScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentScore)
	}
	return context.RetData(c, "")
}
